package com.Yukiha.gachamod.gachaMenu.client.gui.pack;

import com.Yukiha.gachamod.Data.GachaSavedData;
import com.Yukiha.gachamod.Data.PlayerGachaData;
import com.Yukiha.gachamod.gachaMenu.GachaBookMenuProvider;
import com.Yukiha.gachamod.network.ClientboundSyncGachaDataPacket;
import com.Yukiha.gachamod.network.ModNetworkHandler;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkHooks;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.function.Supplier;

public class OpenGachaBookPacket {
    private final UUID playerUUID;

    public OpenGachaBookPacket(UUID uuid) {
        this.playerUUID = uuid;
    }

    public static void encode(OpenGachaBookPacket msg, FriendlyByteBuf buf) {
        buf.writeUUID(msg.playerUUID);
    }

    public static OpenGachaBookPacket decode(FriendlyByteBuf buf) {
        return new OpenGachaBookPacket(buf.readUUID());
    }

    public static void handle(OpenGachaBookPacket msg, Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            ServerPlayer sender = ctx.get().getSender();
            if (sender == null) return;

            ServerLevel level = sender.serverLevel();
            UUID targetUuid = msg.playerUUID;

            // 从服务端存档获取该玩家的模型数据
            Set<String> modelSet = GachaSavedData.get(level).getModels(targetUuid);
            List<String> models = new ArrayList<>(modelSet); // 转换成 List 便于排序或分页

            // 同步客户端缓存（可选：根据你是否有同步包）
            //PlayerGachaData data = GachaSavedData.get(sender.serverLevel()).getPlayerData(msg.playerUUID);
            //ModNetworkHandler.sendTo(sender, new ClientboundSyncGachaDataPacket(data.getAllDrawnModels()));


            // 传入 UUID 打开菜单（将 UUID 写入 buffer）
            NetworkHooks.openScreen(sender, new GachaBookMenuProvider(targetUuid), buf -> {
                buf.writeUUID(targetUuid);
            });
        });
        ctx.get().setPacketHandled(true);
    }

}
